package cn.com.wxd.service.rss;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

import cn.com.wxd.service.rss.entity.ItemEntity;
import cn.com.wxd.service.rss.entity.RssEntity;

import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Description;
import com.sun.syndication.feed.rss.Item;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.WireFeedOutput;
import com.sun.syndication.io.XmlReader;

/**
 * Title:RssUtil.java
 * Description:该类为单例懒加载方式，在使用时自动加载或刷新此类的缓存
 * 
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-8-1 下午2:41:52
 *
 * @author WangXuDong
 * @version 1.0
 */
public class RomeRSSUtil {
	//private static final Logger log = LoggerFactory.getLogger(RomeRssUtil.class);
	/*
	 * 根据链接地址得到数据   
	 * @param url RSS形式的xml文件   
	 * @throws IllegalArgumentException   
	 * @throws FeedException   
	 */    
	public static RssEntity parseRssXml(URL url) throws IOException, IllegalArgumentException, FeedException{
			SyndFeedInput input = new SyndFeedInput();
			SyndFeed feed;
			URLConnection conn;
			conn = url.openConnection();
			String content_encoding = conn.getHeaderField("Content-Encoding");
			if (content_encoding != null && content_encoding.contains("gzip")) {
				GZIPInputStream gzin = new GZIPInputStream(conn.getInputStream());
				feed = input.build(new XmlReader(gzin));
			} else {
				feed = input.build(new XmlReader(conn.getInputStream()));
			}
			return fullRssEntity(feed);
	}
	/*
	 * 根据xml文件得到数据   
	 * @param file文件  RSS形式的xml文件   
	 * @throws IllegalArgumentException   
	 * @throws FeedException   
	 */    
	public static RssEntity parseRssFile(File file) throws IOException, IllegalArgumentException, FeedException{        
			SyndFeedInput input = new SyndFeedInput();
			SyndFeed feed = null;
			feed = input.build(new XmlReader(file));
			return fullRssEntity(feed);
	}
	/**
	 * 生成Rss 字符串
	 * @throws IOException 
	 * @throws FeedException 
	 * @throws IllegalArgumentException 
	 */
	public static String generateRSSString(RssEntity rssEntity) throws IOException, IllegalArgumentException, FeedException {
		/* 根据Channel源码提供的英文,Channel对象有两个构造器，一个默认的无参构造器用于clone对象，一个是有参的
		 * 我们自己指定的必须使用有参数的（因为我们需要许可证），指构造方法必须要创建一个type（版本），这个type不能随便写，必须要以rss_开头的版本号   
		 * Licensed under the Apache License, Version 2.0 (the "License");
		 * 因为当前版本是2.0，所以就是rss_2.0，必须是rss_2.0否则会抛异常，该源码中写的已经很明白。   
		 */
		Channel channel = new Channel("rss_2.0");
		channel.setTitle(rssEntity.getTitle());
		channel.setDescription(rssEntity.getDescription());
		channel.setLink(rssEntity.getLink());  
		channel.setEncoding(rssEntity.getEncoding());
		channel.setLanguage(rssEntity.getLanguage());
		channel.setTtl(rssEntity.getTtl());     
		channel.setCopyright(rssEntity.getCopyright());
		channel.setPubDate(rssEntity.getPubDate());
		List<Item> items = new ArrayList<Item>();
		List<ItemEntity> ies = rssEntity.getItems();
		for (int i = 0; i < ies.size(); i++) {
			Item item = new Item();
			ItemEntity ie = ies.get(i);
			item.setAuthor(ie.getAuthor());
			item.setTitle(ie.getTitle());
			item.setPubDate(ie.getPubDate());
			item.setComments(ie.getComments());
			item.setLink(ie.getLink());
			//新建一个Description，它是Item的描述部分
			Description description = new Description();
			description.setValue(ie.getDescription());
			item.setDescription(description);
			items.add(item);
		}
		channel.setItems(items);
		WireFeedOutput out = new WireFeedOutput();        
        String xml=out.outputString(channel);
        return xml;
           
	}
	/**
	 * 生成Rss 字符串
	 * @param xmlPath 输出的xml文件地址或文件
	 * @throws IOException 
	 * @throws FeedException 
	 * @throws IllegalArgumentException 
	 */
	public static void generateRSSFile(RssEntity rssEntity,String xmlPath) throws IOException, IllegalArgumentException, FeedException {
		if(xmlPath==null){
			throw new IOException("文件地址不存在，不能为NULL");
		}
		File f = new File(xmlPath);
		if(!f.exists()){
			f.mkdirs();
			if(f.isFile()){
				f.createNewFile();
			}
		}
		String xmlStr = generateRSSString(rssEntity);
		FileWriter fileWritter = new FileWriter(f.getName(),true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        bufferWritter.write(xmlStr);
        bufferWritter.close();
	}
	/**
	 * 填充RssEntity
	 * @param feed
	 * @return
	 */
	private static RssEntity fullRssEntity(SyndFeed feed) {
		RssEntity re = new RssEntity();
		re.setTitle(feed.getTitle());
		re.setCopyright(feed.getCopyright());
		re.setDescription(feed.getDescription());
		re.setEncoding(feed.getEncoding());
		re.setLanguage(feed.getLanguage());
		re.setLink(feed.getLink());
		re.setPubDate(feed.getPublishedDate());
		re.setCategories(feed.getCategories());
		List<ItemEntity> ies = new ArrayList<>();
		List entries = feed.getEntries();//得到所有的标题<title></title>
		for(int i=0; i < entries.size(); i++) {
			SyndEntry entry = (SyndEntry)entries.get(i);
			ItemEntity ie = new ItemEntity();
			ie.setAuthor(entry.getAuthor());
			ie.setCategorys(entry.getCategories());
			ie.setDescription(entry.getDescription().getValue());
			ie.setLink(entry.getLink());
			ie.setPubDate(entry.getPublishedDate());
			ie.setTitle(entry.getTitle());
			ies.add(ie);
		}
		re.setItems(ies);
		return re;
	}
}
